import { Injectable } from '@nestjs/common';
import * as fs from 'fs/promises';
import * as path from 'path';

@Injectable()
export class FileStorageService {
  async readJsonFile(filePath: string): Promise<any> {
    try {
      const fullPath = path.join(process.cwd(), filePath);
      const data = await fs.readFile(fullPath, 'utf8');
      return JSON.parse(data);
    } catch (error) {
      if (error.code === 'ENOENT') {
        // 如果文件不存在，返回带有空数组的对象
        const filename = path.basename(filePath, '.json');
        return { [filename]: [] };
      }
      throw error;
    }
  }

  async writeJsonFile(filePath: string, data: any): Promise<void> {
    const fullPath = path.join(process.cwd(), filePath);
    const dirPath = path.dirname(fullPath);
    
    // 确保目录存在
    await fs.mkdir(dirPath, { recursive: true });
    
    await fs.writeFile(
      fullPath,
      JSON.stringify(data, null, 2),
      'utf8'
    );
  }
}
